import React, { Component, createRef, forwardRef } from "react";

// ref如果加在元素上面，那么可以直接获取到元素的dom节点。
// 必须要在加载完以后去获取

// ref如果加在类组件上面，那么可以获取到子组件的实例

// ref如果加在函数组件上面，那么需要配合forwardRef可以获取到子组件的dom节点
class Child extends Component {
  state = {
    count: 1,
  };
  render() {
    return <div>child子组件 - {this.state.count}</div>;
  }
}

const Child2 = forwardRef((props, ref) => {
  return <div ref={ref}>child2子组件</div>;
});

class App extends Component {
  state = {};

  box = createRef();
  child = createRef();
  child2 = createRef();

  render() {
    return (
      <>
        <h2>ref</h2>
        <div ref={this.box}>123</div>

        <hr />

        <Child ref={this.child} />

        <hr />

        <Child2 ref={this.child2} />
      </>
    );
  }

  componentDidMount() {
    // console.log(this.box.current);
    // console.log(this.child.current.state.count);
    console.log(this.child2.current);
  }
}

export default App;
